"""
Form fields for markups 
"""
from django import forms
from django.utils.translation import ugettext as _
from django.forms.util import ValidationError
import dmarkups 
import dmarkups.models
import dmarkups.widgets

class MarkupChooseField(forms.CharField):
    # widget? see __init__  
    markup_choices = None
    def __init__(self, **kwargs):
        self.markup_choices = kwargs.pop('markup_choices', [])
        default_kwargs = {}
        if len(self.markup_choices) <= 1:
            default_kwargs['widget'] = dmarkups.widgets.MarkupChoose(markup_choices=self.markup_choices)
        else:
            default_kwargs['widget'] = dmarkups.widgets.MarkupChoose(markup_choices=self.markup_choices)
        
        default_kwargs.update(kwargs)
        super(MarkupChooseField, self).__init__(**default_kwargs)
   
    def clear(self, value):
        print "validation of choose field!"
        return value

class MarkupContentField(forms.CharField):
    widget = dmarkups.widgets.MarkupContent
   
    def clear(self, value):
        print "validation of content field!"
        return value    
    # TODO: Validation
    # TODO: Preview? How? Ajax & JS? What about Non-JS?

class MarkupField(forms.MultiValueField):
    """
    A Field that combines the markup choose field, and the content field.
    
    Compresses the three default fields to given `markup_model`.
    Values of compression are (selected_markup, content, primary_key)
    """
    
    # widget? See __init__
    qs = None
    fields = None
    markup_model = dmarkups.models.Markup # Defaults to this
    required_content = None
    markup_choices = None
    
    def __init__(self, **kwargs):
        # TODO: Do we really need this queryset?
        self.qs = kwargs.pop('queryset', None)
        self.markup_model = kwargs.pop('markup_model', None) or self.markup_model
        self.required_content = kwargs.pop('required', True)
        
        include_markups = kwargs.pop('include_markups', None)
        exclude_markups = kwargs.pop('exclude_markups', None)
        self.markup_choices = kwargs.pop('markup_choices', None) or dmarkups.MARKUP_CHOICES
         
        if include_markups is not None:
            self.markup_choices = [mc for mc in self.markup_choices if mc[0] in include_markups]
            
        if exclude_markups is not None:
            self.markup_choices = [mc for mc in self.markup_choices if mc[0] not in exclude_markups]
        
        default_kwargs = {'widget': dmarkups.widgets.MarkupWriter(markup_model=self.markup_model, markup_choices=self.markup_choices),
                          'required': False,
                          'fields': (MarkupChooseField(required=False, markup_choices=self.markup_choices),
                                     MarkupContentField(required=False), 
                                     forms.IntegerField(required=False))} # TODO: Restriction of PK: Maybe we don't want pk/id to be restricted on Integers?
        #default_kwargs.update(kwargs) # TODO: NEXT: Whaat?
        
        super(MarkupField, self).__init__(**default_kwargs)
        
    def clean(self, value):
        selected_markup, content, primary_key = value
        if self.required_content and (len(content) == 0 or len(selected_markup) == 0):
            raise ValidationError(self.error_messages['required'])
        return super(MarkupField, self).clean(value)
    
    def compress(self, value):
        """Compresses the values given to the markup_model, and saves it.
         
        `value` must be tuple (selected_markup, content, primary_key)
        """

        selected_markup, content, primary_key = value
        try:
            markup = self.markup_model.objects.get(pk = primary_key)
        except self.markup_model.DoesNotExist:
            markup = self.markup_model()
        
        # TODO: Do we need more validation here?
        markup.markup = selected_markup
        markup.content = content
        
        # TODO: Saving auto rendering, good idea?: We rely on it here.
        markup.save()
        
        return markup